package com.lechuang.cunpinke.fragment;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;

import com.lechuang.cunpinke.activity.BaseActivity;
import com.lechuang.cunpinke.manager.ToastManager;
import com.lechuang.cunpinke.utils.DialogHelp;

import rx.Subscription;

/**
 * 作者：尹松涛
 * 邮箱：yinsongtaoshmily@outlook.com
 * 日期：2017/9/26
 * 时间：14:12
 */

public abstract class BaseFragment extends Fragment {
    private boolean _isVisible = true;
    private ProgressDialog waitDialog;
    protected Subscription subscription;
    private BaseActivity baseActivity;

    public void setBaseActivity(BaseActivity activity) {
        baseActivity = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public ProgressDialog showWaitDialog(String message) {
        if (_isVisible) {
            if (waitDialog == null) {
                waitDialog = DialogHelp.getWaitDialog(baseActivity, message);
            }
            if (waitDialog != null) {
                waitDialog.setMessage(message);
                waitDialog.show();
            }
            return waitDialog;
        }
        return null;
    }

    public void hideWaitDialog() {
        if (_isVisible && waitDialog != null) {
            try {
                if (waitDialog.isShowing())
                    waitDialog.dismiss();
                waitDialog = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 显示一个时间较长的toast信息
     *
     * @param id
     */
    public void showLongToast(int id) {
        ToastManager.getInstance().showLongToast(id);
    }

    /**
     * 显示一个时间较长的toast信息
     *
     * @param msg
     */
    @JavascriptInterface
    public void showLongToast(String msg) {
        ToastManager.getInstance().showLongToast(msg);
    }

    /**
     * 显示一个时间较短的toast信息
     *
     * @param id
     */
    public void showShortToast(int id) {
        ToastManager.getInstance().showShortToast(id);
    }


    /**
     * 显示一个时间较短的toast信息
     *
     * @param msg
     */
    @JavascriptInterface
    public void showShortToast(String msg) {
        ToastManager.getInstance().showShortToast(msg);
    }

    @Override
    public void onDestroy() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        super.onDestroy();
    }
}
